//
//  ProductViewController.m
//  PurchasingMeeting
//
//  Created by zhuang yihang on 7/12/13.
//  Copyright (c) 2013 YX. All rights reserved.
//

#import "ProductViewController.h"
#import "ProductThumbView.h"
#import "ProductDetailViewController.h"
#import "DemoTableController.h"
#import "FPPopoverController.h"
#import "SDImageView+SDWebCache.h"
#import "TipView.h"
#import "TKImageCache.h"

#import "DataManager.h"
#import "UIHelper.h"

#import "PopupView.h"

#import "PMGlobal.h"
#import "ProductObject.h"
#import "ZbarViewController.h"

#import "ProductDetailViewControllerEx.h"

#define PRONUM 20
@interface ProductViewController ()<UIGestureRecognizerDelegate>{
    NSMutableArray *filterBtns_;
    
    NSArray *keyCategories_;
    
    
    TKImageCache *imageCache_;
}

@end

@implementation ProductViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        [self setNavTitle:@"商品订购"];
#ifdef DHH_iOS
        UITabBarItem *tabBarItem = [[UITabBarItem alloc] initWithTitle:self.title image:[[UIHelper getInstance] getBundleImage:@"main_product_iphone.png"] tag:0];
        self.tabBarItem = tabBarItem;
#endif
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(toDetail:) name:@"goToProductDetail" object:nil];
      //  [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dismiss:) name:@"dismiss" object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addsearch:) name:@"addsearch" object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(index:) name:@"index" object:nil];
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(showtip:) name:@"showtip" object:nil];
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(setsearchbtn1:) name:@"setsearchbtn1" object:nil];

        
        keyCategories_ = [[DataManager sharedManager] getKeyCategories];
        
        imageCache_ = [[TKImageCache alloc] initWithCacheDirectoryName:@"image"];
        imageCache_.notificationName = @"product_image";
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(product_image:) name:@"product_image" object:nil];
        
        KeyFilter = [[NSMutableArray alloc]init];
    }
    return self;
}

- (void)dealloc{
    [imageCache_ cancelOperations];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    UITapGestureRecognizer *tapGr = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(viewTapped:)];
    tapGr.delegate = self;
    [self.view addGestureRecognizer:tapGr];
    
    if ([[[UIDevice currentDevice]systemVersion]floatValue]>=7.0)
    {
        self.automaticallyAdjustsScrollViewInsets=NO;
    }
    UIButton *zbar = [UIButton buttonWithType:UIButtonTypeCustom];
    UIImage *img = [[UIHelper getInstance] getBundleImage:@"zbar.png"];
    [zbar setBackgroundImage:img forState:UIControlStateNormal];
    zbar.frame = CGRectMake(10, 10, img.size.width, img.size.height);
    zbar.tag = 13;
    [zbar addTarget:self action:@selector(zbar:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *r = [[UIBarButtonItem alloc] initWithCustomView:zbar];
    
    UIButton *b = [UIButton buttonWithType:UIButtonTypeCustom];
    img = [[PMGlobal getInstance]getretimage];
    [b setImage:img forState:UIControlStateNormal];
    b.frame = CGRectMake(10, 10, img.size.width, img.size.height);
    [b addTarget:self action:@selector(ret) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *left = [[UIBarButtonItem alloc] initWithCustomView:b];
    self.navigationItem.leftBarButtonItem = left;
    self.navigationItem.rightBarButtonItem = r;

   // [self.navigationController.navigationBar setBackgroundImage:[[UIHelper getInstance] getBundleImage:@"navigationbar1.png"] forBarMetrics:UIBarMetricsDefault];
    
    //[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(refreshorder:) name:@"refreshorder" object:nil];
    searchproduct = [[NSMutableArray alloc]init];
    
    NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
    NSString *setsearchstr = [def objectForKey:@"setsearchbtn"];
    if ([setsearchstr isEqualToString:@"1"]) {
        isclick = YES;
    }
    else
    {
        isclick = NO;
    }
#ifdef DHH_iOS
    
    img = [[UIHelper getInstance] getBundleImage:@"iphone_tint1.png"];
    filtertint = [[UIImageView alloc]initWithImage:img];
    if ([[[UIDevice currentDevice]systemVersion]floatValue]>=7.0)
    {
        filtertint.frame = CGRectMake(0, 64, img.size.width+10, img.size.height+10);
    }
    else
    {
        filtertint.frame = CGRectMake(0, 0, img.size.width+10, img.size.height+10);
    }
    filtertint.userInteractionEnabled = YES;
    [self.view addSubview:filtertint];
    
    img = [[UIHelper getInstance] getBundleImage:@"iphone_tint.png"];
    tint = [[UIImageView alloc]initWithImage:img];
    tint.frame = CGRectMake(0, 0, img.size.width, img.size.height);
    tint.userInteractionEnabled = YES;
    tint.top = filtertint.bottom;
    [self.view addSubview:tint];
    
    search = [[UITextField alloc]initWithFrame:CGRectMake(0, 0, 150, 23)];
    search.backgroundColor = [UIColor clearColor];
    search.center = CGPointMake(self.view.width/2, img.size.height/2);
    search.delegate = self;
    search.keyboardType=UIKeyboardTypeNumbersAndPunctuation;
    search.returnKeyType = UIReturnKeySearch;
    [tint addSubview:search];
    
    issearch = NO;
    isclear = YES;
    num = PRONUM;
#else
        
    issearch = NO;
    isclear = YES;
    num = PRONUM;
    
        
   // NSArray *arr = [[NSArray alloc]initWithObjects:r,r1, nil];

    UIImage *tintImage = [[UIHelper getInstance] getBundleImage:@"detail_tint.png"];
    tintImage = [tintImage resizableImageWithCapInsets:UIEdgeInsetsMake(0, 16, 0, 16)];
    
    tint = [[UIImageView alloc]initWithImage:tintImage];
    tint.width = 1024;
    if ([[[UIDevice currentDevice]systemVersion]floatValue]>=7.0)
    {
        tint.top = 64;
    }
    tint.userInteractionEnabled = YES;
    [self.view addSubview:tint];
#endif
    
    filterBtns_ = [NSMutableArray array];
#ifdef DHH_iOS
    filterscroll = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, filtertint.width, filtertint.height)];
    filterscroll.delegate = self;
    [filtertint addSubview:filterscroll];
    
    for ( int i = 0; i < keyCategories_.count; i++ ) {
        UIButton *b = [[UIHelper getInstance] createButtonByFrame:CGRectMake(0, 0, 120, filtertint.height)];
        [b setImage:[[UIHelper getInstance] getBundleImage:@"order_next.png"] forState:UIControlStateNormal];
        [filterscroll addSubview:b];
        [b setBackgroundColor:[UIColor clearColor]];
        [b setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        b.titleLabel.font = [UIFont systemFontOfSize:14];
        b.titleLabel.adjustsFontSizeToFitWidth=YES;
        //  b.backgroundColor = [[UIHelper getInstance] getRandomColor];
        b.left = (b.width+10)*i;
        [b addTarget:self action:@selector(keyClicked:) forControlEvents:UIControlEventTouchUpInside];
        [filterBtns_ addObject:b];
        b.tag = [[keyCategories_ objectAtIndex:i] intValue];
        b.imageEdgeInsets = UIEdgeInsetsMake(0, 90, 0, 0);
        
        KeyObject* firstkey = [[[DataManager sharedManager]getKeyObjects:(i+1)]objectAtIndex:0];
        [b setTitle:firstkey.keyName forState:UIControlStateNormal];
        [KeyFilter addObject:firstkey];
        CGSize s = [firstkey.keyName sizeWithFont:b.titleLabel.font];
        if (s.width>98) {
            b.imageEdgeInsets = UIEdgeInsetsMake(0, 90+(98-56)/2, 0, 0);
        }
        else
        {
            b.imageEdgeInsets = UIEdgeInsetsMake(0, 90+(s.width-56)/2, 0, 0);
        }
        filterscroll.contentSize = CGSizeMake(b.right, filtertint.height);
    }
    
    //初始化菜单
    for ( int i = 0; i < keyCategories_.count; i++ ) {
        
        [self updateKeyButton:i+1];
    }
    
    UIImage *bgImage = [[UIHelper getInstance] getBundleImage:@"iphone_back.png"];
    self.view.backgroundColor = [UIColor colorWithPatternImage:bgImage];
#else
    for ( int i = 0; i < keyCategories_.count; i++ ) {
        UIButton *b = [[UIHelper getInstance] createButtonByFrame:CGRectMake(0, 0, 120, tint.height)];
        [b setImage:[[UIHelper getInstance] getBundleImage:@"order_next.png"] forState:UIControlStateNormal];
        [tint addSubview:b];
        
        [b setBackgroundColor:[UIColor clearColor]];
        [b setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        b.titleLabel.font = [UIFont systemFontOfSize:14];
      //  b.backgroundColor = [[UIHelper getInstance] getRandomColor];
        b.titleLabel.adjustsFontSizeToFitWidth=YES;
        b.left = (b.width+10)*i;
        [b addTarget:self action:@selector(keyClicked:) forControlEvents:UIControlEventTouchUpInside];
        [filterBtns_ addObject:b];
        b.tag = [[keyCategories_ objectAtIndex:i] intValue];
       // b.imageEdgeInsets = UIEdgeInsetsMake(0, 90, 0, 0);
        
        KeyObject* firstkey = [[[DataManager sharedManager]getKeyObjects:(i+1)]objectAtIndex:0];
        [b setTitle:firstkey.keyName forState:UIControlStateNormal];
        CGSize s = [firstkey.keyName sizeWithFont:b.titleLabel.font];
        if (s.width>98) {
            b.imageEdgeInsets = UIEdgeInsetsMake(0, 90+(98-56)/2, 0, 0);
        }
        else
        {
            b.imageEdgeInsets = UIEdgeInsetsMake(0, 90+(s.width-56)/2, 0, 0);
        }
        [KeyFilter addObject:firstkey];
    }

    //初始化菜单
    for ( int i = 0; i < keyCategories_.count; i++ ) {
        
        [self updateKeyButton:i+1];
    }
    
//    if (keyCategories_.count>0) {
//        UIButton *firstOne = [filterBtns_ objectAtIndex:0];
//       [self updateKeyButton:firstOne withIndex:0];
//    }
//   
    
    UIImage *bgImage = [[UIHelper getInstance] getBundleImage:@"suit_bg.jpg"];
    self.view.backgroundColor = [UIColor colorWithPatternImage:bgImage];
    
    img = [[UIHelper getInstance] getBundleImage:@"detail_codesearch.png"];
    searchimage=[[UIImageView alloc]initWithImage:img];
    searchimage.frame = CGRectMake(0, 0, img.size.width*4/3, img.size.height*4/3);
    searchimage.center = CGPointMake(780, tint.height/2);
    searchimage.userInteractionEnabled=YES;
    [tint addSubview:searchimage];
    
    search = [[UITextField alloc]initWithFrame:CGRectMake(0, 0, 130, 40)];
    search.backgroundColor = [UIColor clearColor];
    if ([[[UIDevice currentDevice]systemVersion]floatValue]>=7.0)
    {
        search.center = CGPointMake(105, searchimage.height/2);
    }
    else
    {
        search.center = CGPointMake(105, 32);
    }
    if (isclick == YES) {
        search.placeholder = SEARCH_CODENAME;
    }
    else
    {
        search.placeholder = SEARCH_SIMCODE;
    }
    search.delegate = self;
    search.keyboardType=UIKeyboardTypeNumbersAndPunctuation;
    search.returnKeyType = UIReturnKeySearch;
    [searchimage addSubview:search];
    
    UIView *clickview = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 40, 40)];
    clickview.backgroundColor = [UIColor clearColor];
    clickview.userInteractionEnabled=YES;
    [searchimage addSubview:clickview];
    
    UITapGestureRecognizer *clicktap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(clicktap:)];
    [clickview addGestureRecognizer:clicktap];
    
    
    img = [[UIHelper getInstance] getBundleImage:@"anniu.png"];
    UIButton *comfirmSearch = [UIButton buttonWithType:UIButtonTypeCustom];
    comfirmSearch.frame = CGRectMake(0, 0, 60, 40);
    [comfirmSearch setBackgroundImage:img forState:UIControlStateNormal];
    [comfirmSearch setTitle:@"搜索" forState:UIControlStateNormal];
    comfirmSearch.center = CGPointMake(960, tint.height/2);
    comfirmSearch.left = searchimage.right+6;
    [comfirmSearch addTarget:self action:@selector(comfirmSearch:) forControlEvents:UIControlEventTouchUpInside];
    [tint addSubview:comfirmSearch];
    
    UIButton *select = [UIButton buttonWithType:UIButtonTypeCustom];
    select.frame = CGRectMake(0, 0, 80, 40);
    [select setBackgroundImage:img forState:UIControlStateNormal];
    [select setTitle:@"切换" forState:UIControlStateNormal];
    select.center = CGPointMake(960, tint.height/2);
    select.left = comfirmSearch.right+5;
    [select addTarget:self action:@selector(selectcode:) forControlEvents:UIControlEventTouchUpInside];
    [tint addSubview:select];

#endif
    
    KeyObject* key = self.keyobj;
    if (key) {
        [KeyFilter replaceObjectAtIndex:0 withObject:key];
        
        [self updateKeyButton:1];
    }
    
    [self refresh];
    
   // [self refresh:pserialstr style:nil];
    
}


- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:NO];
}


-(void)refresh
{
    issearch = NO;
    page = 0;
    num = PRONUM;
    isnoobj = NO;

    [scroll removeFromSuperview];
#ifdef DHH_iOS
    int maxCol = 2;
    float xOffset = 10;
    float yOffset = 20;
    UIImage *img = [[UIHelper getInstance] getBundleImage:@"iphone_tint.png"];
    if ([[[UIDevice currentDevice]systemVersion]floatValue]>=7.0)
    {
        scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, img.size.height, 320,self.view.height-tint.bottom-10)];
    }
    else
    {
        scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, img.size.height, 320,460-tint.bottom-10-44)];
    }
    scroll.backgroundColor = [UIColor clearColor];
    scroll.top = tint.bottom+10;
    scroll.delegate = self;
    [self.view addSubview:scroll];
    
    float height = 0;
    product = [[DataManager sharedManager] getProduct:KeyFilter page:page pageSize:num];
    for (int i = 0; i < num&& i<product.count; i++) {
//        if (style) {
//            product = [[DataManager sharedManager] getProduct:nil type:pserial style:style page:page pageSize:20];
//        }
//        else
//        {
//            product = [[DataManager sharedManager] getProduct:nil type:pserial page:page pageSize:20];
//        }

            ProductObject *obj = [product objectAtIndex:i];
            ProductThumbView *v = [[ProductThumbView alloc] initWithProduct:obj tag:0];
            v.tag = 100+i;
            NSString *path = [[[PMGlobal getInstance] getImageURL] stringByAppendingPathComponent:obj.pThumbURL];
        path = [path stringByReplacingOccurrencesOfString:@"http:/" withString:@"http://"];
            UIImage *img = [imageCache_ imageForKey:obj.pThumbURL url:[NSURL URLWithString:path] queueIfNeeded:YES tag:i+100];
        if (img==nil) {
            v.imageview.image = [[UIHelper getInstance] getBundleImage:@"product_placeholder.jpg"];
        }
        else
        {
            v.imageview.image = img;
        }
        
            [scroll addSubview:v];
            
            int row = i / maxCol;
            int col = i % maxCol;
            
            v.left = xOffset + col * (v.width + 10);
            v.top = yOffset + row * (v.height + 10);
            
            height = v.bottom+10;
    }
    
    scroll.contentSize = CGSizeMake(scroll.width, height+yOffset);
    
    refreshView = [[EGORefreshTableFooterView alloc]  initWithFrame:CGRectMake(0, 0, 320, 0)];
    refreshView.delegate = self;
    refreshView.top = scroll.bottom;
    
    [scroll addSubview:refreshView];
    [self setRefreshView];
    
    view = [[UIView alloc]initWithFrame:CGRectMake(35, 35, 60, 80)];
    view.backgroundColor = [UIColor grayColor];
    view.hidden = YES;
    [self.view addSubview:view];
#else
    int maxCol = 5;
    float xOffset = 50;
    float yOffset = 30;
    if ([[[UIDevice currentDevice]systemVersion]floatValue]>=7.0)
    {
        scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 10+tint.bottom, 1024,748-44-64)];
    }
    else
    {
        scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 10+tint.bottom, 1024,748-44-54)];
    }
    scroll.backgroundColor = [UIColor clearColor];
    scroll.delegate = self;
    [self.view addSubview:scroll];
    
    float height = 0;
    
    product = [[DataManager sharedManager] getProduct:KeyFilter page:page pageSize:num];
    
    for (int i = 0; i < num && i<product.count; i++) {
//        if (style) {
//            product = [[DataManager sharedManager] getProduct:nil type:pserial style:style page:page pageSize:20];
//        }
//        else
//        {
//            product = [[DataManager sharedManager] getProduct:nil type:pserial page:page pageSize:20];
//        }
        

            ProductObject *obj = [product objectAtIndex:i];
            ProductThumbView *v = [[ProductThumbView alloc] initWithProduct:obj tag:0];
            v.tag = 100+i;
        NSString *s = [[PMGlobal getInstance] getImageURL];
            NSString *path = [s stringByAppendingPathComponent:obj.pThumbURL];
        path = [path stringByReplacingOccurrencesOfString:@"http:/" withString:@"http://"];
            UIImage *img = [imageCache_ imageForKey:obj.pThumbURL url:[NSURL URLWithString:path] queueIfNeeded:YES tag:i+100];
        
        if (img==nil || ![[PMGlobal getInstance]isImageEnable]) {
            img = [[UIHelper getInstance] getBundleImage:@"product_placeholder.jpg"];;
        }
        v.imageview.image = img;

            [scroll addSubview:v];
            
            int row = i / maxCol;
            int col = i % maxCol;
            
            v.left = xOffset + col * (v.width + 20);
            v.top = yOffset + row * (v.height + 20);
            
            height = v.bottom;
            
    }
    
    scroll.contentSize = CGSizeMake(scroll.width, height+yOffset);
    
    refreshView = [[EGORefreshTableFooterView alloc]  initWithFrame:CGRectMake(0, 0, 1024, 0)];
    refreshView.delegate = self;
    refreshView.top = scroll.bottom;
    
    [scroll addSubview:refreshView];
    [self setRefreshView];
    
    view = [[UIView alloc]initWithFrame:CGRectMake(35, 35, 60, 80)];
    view.backgroundColor = [UIColor grayColor];
    view.hidden = YES;
    [self.view addSubview:view];
#endif
}
-(void)refresh1
{
    isnoobj = NO;
#ifdef DHH_iOS
    searchproduct = [[DataManager sharedManager] searchProductWithCode:search.text];
    NSLog(@"%@,%d",search.text,searchproduct.count);
    
    issearch = YES;
    page = 0;
    num = PRONUM;
    
    [scroll removeFromSuperview];
    int maxCol = 2;
    float xOffset = 10;
    float yOffset = 20;
    UIImage *img = [[UIHelper getInstance] getBundleImage:@"iphone_tint.png"];
    if ([[[UIDevice currentDevice]systemVersion]floatValue]>=7.0)
    {
        scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, img.size.height, 320,self.view.height-tint.bottom-10)];
    }
    else
    {
        scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, img.size.height, 320,460-tint.bottom-10-44)];
    }
    scroll.backgroundColor = [UIColor clearColor];
    scroll.top = tint.bottom+10;
    scroll.delegate = self;
    [self.view addSubview:scroll];
    
    float height = 0;
    
    for (int i = 0; i < num; i++) {
        if(i<searchproduct.count)
        {
            // product = [[DataManager sharedManager] getProduct:nil page:page pageSize:PRONUM];
            ProductObject *obj = [searchproduct objectAtIndex:i];
            ProductThumbView *v = [[ProductThumbView alloc] initWithProduct:obj tag:0];
            
            v.tag = 100+i;
            NSString *path = [[[PMGlobal getInstance] getImageURL] stringByAppendingPathComponent:obj.pThumbURL];
            path = [path stringByReplacingOccurrencesOfString:@"http:/" withString:@"http://"];
            UIImage *img = [imageCache_ imageForKey:obj.pThumbURL url:[NSURL URLWithString:path] queueIfNeeded:YES tag:i+100];
            if (img==nil) {
                v.imageview.image = [[UIHelper getInstance] getBundleImage:@"product_placeholder.jpg"];
            }
            else
            {
                v.imageview.image = img;
            }
            
            [scroll addSubview:v];
            
            int row = i / maxCol;
            int col = i % maxCol;
            
            v.left = xOffset + col * (v.width + 10);
            v.top = yOffset + row * (v.height + 10);
            
            height = v.bottom+10;
        }
    }
    
    scroll.contentSize = CGSizeMake(scroll.width, height+yOffset);
    
    refreshView = [[EGORefreshTableFooterView alloc]  initWithFrame:CGRectMake(0, 0, 320, 0)];
    refreshView.delegate = self;
    refreshView.top = scroll.bottom;
    
    [scroll addSubview:refreshView];
    [self setRefreshView];
    
    view = [[UIView alloc]initWithFrame:CGRectMake(35, 35, 60, 80)];
    view.backgroundColor = [UIColor grayColor];
    view.hidden = YES;
    [self.view addSubview:view];
#else
    if (isclick==NO) {
        int cnt =[[[DataManager sharedManager]searchProductCountWithSimCode:search.text]intValue];
        if(cnt == 0)
        {
            showMessage(@"没有找到对应简码");
            return;
        }
        else
        {
            searchproduct = [[DataManager sharedManager]searchProductWithSimCode:search.text];
        }
    }
    else
    {
        searchproduct = [[DataManager sharedManager] searchProductWithCode:search.text];
    }
    
    issearch = YES;
    page = 0;
    num = PRONUM;
    
    [scroll removeFromSuperview];
    int maxCol = 5;
    float xOffset = 50;
    float yOffset = 30;
    
    if ([[[UIDevice currentDevice]systemVersion]floatValue]>=7.0)
    {
        scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 10+tint.bottom, 1024,748-44-64)];
    }
    else
    {
        scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 10+tint.bottom, 1024,748-44-54)];
    }
    scroll.backgroundColor = [UIColor clearColor];
    scroll.delegate = self;
    [self.view addSubview:scroll];
    
    float height = 0;
    
    for (int i = 0; i < num&&i<searchproduct.count; i++) {
 
            // product = [[DataManager sharedManager] getProduct:nil page:page pageSize:PRONUM];
            ProductObject *obj = [searchproduct objectAtIndex:i];
            ProductThumbView *v = [[ProductThumbView alloc] initWithProduct:obj tag:0];
            
            v.tag = 100+i;
            NSString *path = [[[PMGlobal getInstance] getImageURL] stringByAppendingPathComponent:obj.pThumbURL];
        path = [path stringByReplacingOccurrencesOfString:@"http:/" withString:@"http://"];
            UIImage *img = [imageCache_ imageForKey:obj.pThumbURL url:[NSURL URLWithString:path] queueIfNeeded:YES tag:i+100];
        
        if (img==nil || ![[PMGlobal getInstance]isImageEnable]) {
            img = [[UIHelper getInstance] getBundleImage:@"product_placeholder.jpg"];;
        }
        v.imageview.image = img;
        
        
            [scroll addSubview:v];
            
            int row = i / maxCol;
            int col = i % maxCol;
            
            v.left = xOffset + col * (v.width + 20);
            v.top = yOffset + row * (v.height + 20);
            
            height = v.bottom;
    }
    
    scroll.contentSize = CGSizeMake(scroll.width, height+yOffset);
    
    refreshView = [[EGORefreshTableFooterView alloc]  initWithFrame:CGRectMake(0, 0, 1024, 0)];
    refreshView.delegate = self;
    refreshView.top = scroll.bottom;
    
    [scroll addSubview:refreshView];
    [self setRefreshView];
    
    view = [[UIView alloc]initWithFrame:CGRectMake(35, 35, 60, 80)];
    view.backgroundColor = [UIColor grayColor];
    view.hidden = YES;
    [self.view addSubview:view];
#endif
}


-(void)ret
{
    refreshView.delegate = nil;
    UIImage *img = [[PMGlobal getInstance]getnavigationbarimage];
    [self.navigationController.navigationBar setBackgroundImage:img forBarMetrics:UIBarMetricsDefault];
    [search removeFromSuperview];
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark 进入细节页面
- (void)toDetail:(NSNotification *)notification{
   // [self.navigationController.navigationBar setBackgroundImage:[[UIHelper getInstance] getBundleImage:@"navigationBar.png"] forBarMetrics:UIBarMetricsDefault];
   // [search removeFromSuperview];
    ProductObject *obj = (ProductObject *)notification.object;
//    ProductDetailViewController *detail = [[ProductDetailViewController alloc] initWithProduct:obj objtag:1 tag:1];
    
    ProductDetailViewControllerEx *detail = [[ProductDetailViewControllerEx alloc] initWithProduct:obj];
    detail.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:detail animated:YES];
}
-(void)next
{
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.1];
    next.transform = CGAffineTransformRotate(next.transform, -90 * M_PI / 180);
    [UIView commitAnimations];
}
-(void)next1
{
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.1];
    next1.transform = CGAffineTransformRotate(next.transform, -90 * M_PI / 180);
    [UIView commitAnimations];
}
-(void)coattype
{
    title.text = @"服装";
}
-(void)pantstype
{
    title.text = @"裤子";
}
-(void)shoetype
{
    title.text = @"鞋子";
}

//请求数据
-(void)reloadData
{
    reloading = YES;
    //新建一个线程来加载数据
    [NSThread detachNewThreadSelector:@selector(requestData)
                             toTarget:self
                           withObject:nil];
}

-(void)requestData
{
    sleep(1);
    //在主线程中刷新UI
    [self performSelectorOnMainThread:@selector(reloadUI)
                           withObject:nil
                        waitUntilDone:NO];
}

-(void)reload
{
#ifdef DHH_iOS
    // [scroll removeFromSuperview];
    [refreshView removeFromSuperview];
    int maxCol = 2;
    float xOffset = 10;
    float yOffset = 20;
    num+=PRONUM;
    // scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 10+[[UIHelper getInstance] getBundleImage:@"detail_tint.png"].size.height, 1024,748-44)];
    // scroll.backgroundColor = [UIColor clearColor];
    // scroll.delegate = self;
    // [self.view addSubview:scroll];
    
    float height = 0;
    if (issearch == NO) {
        page+=1;
        product = [[DataManager sharedManager] getProduct:nil page:page pageSize:PRONUM];
        NSArray * productarr = [[DataManager sharedManager]getProduct:KeyFilter page:page+1 pageSize:PRONUM];
        if (product.count>0) {
            for (int i = num-PRONUM; i < num && i-PRONUM*page<product.count; i++) {
                ProductObject *obj = [product objectAtIndex:i-PRONUM*page];
                ProductThumbView *v = [[ProductThumbView alloc] initWithProduct:obj tag:0];
                
                v.tag = 100+i;
                NSString *path = [[[PMGlobal getInstance] getImageURL] stringByAppendingPathComponent:obj.pThumbURL];
                path = [path stringByReplacingOccurrencesOfString:@"http:/" withString:@"http://"];
                UIImage *img = [imageCache_ imageForKey:obj.pThumbURL url:[NSURL URLWithString:path] queueIfNeeded:YES tag:i+100];
                if (img==nil) {
                    v.imageview.image = [[UIHelper getInstance] getBundleImage:@"product_placeholder.jpg"];
                }
                else
                {
                    v.imageview.image = img;
                }
                
                [scroll addSubview:v];
                
                int row = i / maxCol;
                int col = i % maxCol;
                
                v.left = xOffset + col * (v.width + 10);
                v.top = yOffset + row * (v.height + 10);
                
                height = v.bottom+10;
            }
        }
        if (product.count==PRONUM&&productarr.count!=0) {
            scroll.contentSize = CGSizeMake(scroll.width, height+yOffset);
        }
        else
        {
            showMessage(@"没数据了");
            if (isnoobj == NO) {
                if (height!=0) {
                    scroll.contentSize = CGSizeMake(scroll.width, height+yOffset);
                }
                isnoobj = YES;
            }
            if (scroll.contentSize.height<710) {
                scroll.contentOffset = CGPointMake(0, 0);
            }
            else
            {
                scroll.contentOffset = CGPointMake(0, scroll.contentSize.height-710);
            }
        }

    }
    else
    {
        for (int i = num-PRONUM; i < num ; i++) {
            if(i<searchproduct.count)
            {
                ProductObject *obj = [searchproduct objectAtIndex:i];
                ProductThumbView *v = [[ProductThumbView alloc] initWithProduct:obj tag:0];
                
                
                v.tag = i+100;
                NSString *path = [[[PMGlobal getInstance] getImageURL] stringByAppendingPathComponent:obj.pThumbURL];
                path = [path stringByReplacingOccurrencesOfString:@"http:/" withString:@"http://"];
                UIImage *img = [imageCache_ imageForKey:obj.pThumbURL url:[NSURL URLWithString:path] queueIfNeeded:YES tag:v.tag];
                if (img==nil) {
                    v.imageview.image = [[UIHelper getInstance] getBundleImage:@"product_placeholder.jpg"];
                }
                else
                {
                    v.imageview.image = img;
                }
                
                [scroll addSubview:v];
                
                int row = i / maxCol;
                int col = i % maxCol;
                
                v.left = xOffset + col * (v.width + 10);
                v.top = yOffset + row * (v.height + 10);
                
                height = v.bottom+10;
            }
        }
        if (num<product.count) {
            scroll.contentSize = CGSizeMake(scroll.width, height+yOffset);
        }
        else
        {
            //  scroll.contentSize = CGSizeMake(scroll.width, height+yOffset);
            showMessage(@"没数据了");
            if (isnoobj == NO) {
                if (height!=0) {
                    scroll.contentSize = CGSizeMake(scroll.width, height+yOffset);
                }
                isnoobj = YES;
            }
            if (scroll.contentSize.height<350) {
                scroll.contentOffset = CGPointMake(0, 0);
            }
            else
            {
                scroll.contentOffset = CGPointMake(0, scroll.contentSize.height-350);
            }

        }

    }
    
    refreshView = [[EGORefreshTableFooterView alloc]  initWithFrame:CGRectZero];
    refreshView.delegate = self;
    refreshView.top = scroll.bottom;
    
    [scroll addSubview:refreshView];
#else
    // [scroll removeFromSuperview];
    [refreshView removeFromSuperview];
    int maxCol = 5;
    float xOffset = 50;
    float yOffset = 30;
    num+=PRONUM;
   // scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 10+[[UIHelper getInstance] getBundleImage:@"detail_tint.png"].size.height, 1024,748-44)];
   // scroll.backgroundColor = [UIColor clearColor];
   // scroll.delegate = self;
   // [self.view addSubview:scroll];
    
    float height = 0;
    if (issearch == NO) {
        page+=1;
        product = [[DataManager sharedManager]getProduct:KeyFilter page:page pageSize:PRONUM];
        NSArray * productarr = [[DataManager sharedManager]getProduct:KeyFilter page:page+1 pageSize:PRONUM];
        
        if (product.count>0) {
        
            for (int i = num-PRONUM; i < num && i-PRONUM*page<product.count; i++) {
    //            if (stylestr) {
    //                product = [[DataManager sharedManager] getProduct:nil type:pserialstr style:stylestr page:page pageSize:PRONUM];
    //            }
    //            else
    //            {
    //                product = [[DataManager sharedManager] getProduct:nil type:pserialstr page:page pageSize:PRONUM];
    //            }
                    ProductObject *obj = [product objectAtIndex:i-PRONUM*page];
                    ProductThumbView *v = [[ProductThumbView alloc] initWithProduct:obj tag:0];
                    
                    v.tag = 100+i;
                    NSString *path = [[[PMGlobal getInstance] getImageURL] stringByAppendingPathComponent:obj.pThumbURL];
                path = [path stringByReplacingOccurrencesOfString:@"http:/" withString:@"http://"];
                    UIImage *img = [imageCache_ imageForKey:obj.pThumbURL url:[NSURL URLWithString:path] queueIfNeeded:YES tag:i+100];

                if (img==nil || ![[PMGlobal getInstance]isImageEnable]) {
                    img = [[UIHelper getInstance] getBundleImage:@"product_placeholder.jpg"];;
                }
                v.imageview.image = img;
                
                    [scroll addSubview:v];
                    
                    int row = i / maxCol;
                    int col = i % maxCol;
                    
                    v.left = xOffset + col * (v.width + 20);
                    v.top = yOffset + row * (v.height + 20);
                    
                    height = v.bottom;
            }
            
        }
        else{
            height = scroll.contentSize.height-yOffset;
            [scroll setContentOffset:CGPointMake(scroll.contentOffset.x, scroll.contentOffset.y-70)];
        }
        if (product.count==PRONUM&&productarr.count!=0) {
            scroll.contentSize = CGSizeMake(scroll.width, height+yOffset);
        }
        else
        {
            showMessage(@"没数据了");
            if (isnoobj == NO) {
                if (height!=0) {
                    scroll.contentSize = CGSizeMake(scroll.width, height+yOffset);
                }
                isnoobj = YES;
            }
            if (scroll.contentSize.height<710) {
                scroll.contentOffset = CGPointMake(0, 0);
            }
            else
            {
                scroll.contentOffset = CGPointMake(0, scroll.contentSize.height-710);
            }

        }
        NSLog(@"%f,%f",height,yOffset);
    }
    else
    {
        for (int i = num-PRONUM; i < num && i<searchproduct.count ; i++) {
            ProductObject *obj = [searchproduct objectAtIndex:i];
            ProductThumbView *v = [[ProductThumbView alloc] initWithProduct:obj tag:0];

            v.tag = i+100;
            NSString *path = [[[PMGlobal getInstance] getImageURL] stringByAppendingPathComponent:obj.pThumbURL];
            path = [path stringByReplacingOccurrencesOfString:@"http:/" withString:@"http://"];
            UIImage *img = [imageCache_ imageForKey:obj.pThumbURL url:[NSURL URLWithString:path] queueIfNeeded:YES tag:v.tag];
            if (img==nil || ![[PMGlobal getInstance]isImageEnable]) {
                img = [[UIHelper getInstance] getBundleImage:@"product_placeholder.jpg"];;
            }
            v.imageview.image = img;
            
            [scroll addSubview:v];
            
            int row = i / maxCol;
            int col = i % maxCol;
            
            v.left = xOffset + col * (v.width + 20);
            v.top = yOffset + row * (v.height + 20);
            
            height = v.bottom;
        }
        if (num<searchproduct.count) {
            scroll.contentSize = CGSizeMake(scroll.width, height+yOffset);
        }
        else
        {
            showMessage(@"没数据了");
            if (isnoobj == NO) {
                if (height!=0) {
                    scroll.contentSize = CGSizeMake(scroll.width, height+yOffset);
                }
                isnoobj = YES;
            }
            if (scroll.contentSize.height<710) {
                scroll.contentOffset = CGPointMake(0, 0);
            }
            else
            {
                scroll.contentOffset = CGPointMake(0, scroll.contentSize.height-710);
            }

        }
    }
    
    refreshView = [[EGORefreshTableFooterView alloc]  initWithFrame:CGRectZero];
    refreshView.delegate = self;
    refreshView.top = scroll.bottom;
    
    [scroll addSubview:refreshView];
#endif
}
-(void)reloadUI
{
	reloading = NO;
    
    //停止下拉的动作,恢复表格的便宜
	[refreshView egoRefreshScrollViewDataSourceDidFinishedLoading:scroll];
    //更新界面
    [self reload];
    
    [self setRefreshViewFrame];
}
-(void)setRefreshView
{
#ifdef DHH_iOS
    //如果contentsize的高度比表的高度小，那么就需要把刷新视图放在表的bounds的下面
    int height = MAX(scroll.bounds.size.height, scroll.contentSize.height);
    refreshView.frame =CGRectMake(0.0f, height, 320, scroll.bounds.size.height);
#else
    int height = MAX(scroll.bounds.size.height, scroll.contentSize.height);
    refreshView.frame =CGRectMake(0.0f, height, 1024, scroll.bounds.size.height);
#endif
}

-(void)setRefreshViewFrame
{
    //如果contentsize的高度比表的高度小，那么就需要把刷新视图放在表的bounds的下面
    int height = MAX(scroll.bounds.size.height, scroll.contentSize.height);
    refreshView.frame =CGRectMake(0.0f, height, self.view.frame.size.width, scroll.bounds.size.height);
}

#pragma mark - EGORefreshTableFooterDelegate
//出发下拉刷新动作，开始拉取数据
- (void)egoRefreshTableFooterDidTriggerRefresh:(EGORefreshTableFooterView*)view
{
    [self reloadData];
}
//返回当前刷新状态：是否在刷新
- (BOOL)egoRefreshTableFooterDataSourceIsLoading:(EGORefreshTableFooterView*)view
{
    return reloading;
}
//返回刷新时间
-(NSDate *)egoRefreshTableFooterDataSourceLastUpdated:(EGORefreshTableFooterView *)view
{
    return [NSDate date];
}

#pragma mark - UIScrollView
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    distance = filterscroll.contentOffset.x;
    [refreshView egoRefreshScrollViewDidScroll:scrollView];
}
//松开后判断表格是否在刷新，若在刷新则表格位置偏移，且状态说明文字变化为loading...
-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    [refreshView egoRefreshScrollViewDidEndDragging:scrollView];
    if (!decelerate) {
       // [self updateThumbView];
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
   // [self updateThumbView];
}

//判断哪些thumbView不需要显示图片。关闭图片显示，节约资源
- (void)updateThumbView{
    //CGRect r = CGRectMake(scroll.contentOffset.x, scroll.contentOffset.y, scroll.width, scroll.height);
    /*
    float min = scroll.contentOffset.y;
    float max = scroll.contentOffset.y+scroll.height;
    
    UIImage *placeholder = [[UIHelper getInstance] getBundleImage:@"product_placeholder.jpg"];
    
    for (ProductThumbView *v in scroll.subviews) {
        
        if ([v isKindOfClass:[ProductThumbView class]]) {
            if (v.bottom<min || v.top>max) {
                v.imageview.image = placeholder;
            }else{
                //v.tag = 100+i;
                if (v.imageview.image==nil || v.imageview.image == placeholder) {
                    NSString *path = [[[PMGlobal getInstance] getImageURL] stringByAppendingPathComponent:v.object.pThumbURL];
                    UIImage *img = [imageCache_ imageForKey:v.object.pThumbURL url:[NSURL URLWithString:path] queueIfNeeded:YES tag:v.tag];
                    v.imageview.image = img;
                }else{
                }
                
            }
        }
        
    }
     */
    int page1 = (scroll.contentOffset.y-22)/788;
    for (int i=0; i<page1*PRONUM; i++) {
        ProductThumbView *v = (ProductThumbView *)[scroll viewWithTag:100+i];
        v.imageview.image = [[UIHelper getInstance] getBundleImage:@"product_placeholder.jpg"];
    }
    for (int i=page1*PRONUM; i<(page1+2)*PRONUM; i++) {
        NSArray * arr = [[DataManager sharedManager]getProduct:KeyFilter page:page pageSize:PRONUM];
        NSArray * arr1 = [[DataManager sharedManager]getProduct:KeyFilter page:page+1 pageSize:PRONUM];
        ProductObject *obj;
        if (i-page1*PRONUM<PRONUM) {
            obj = [arr objectAtIndex:i-page1*PRONUM];
        }
        else
        {
            obj = [arr1 objectAtIndex:i-(page1+1)*PRONUM];
        }
        ProductThumbView *v = (ProductThumbView *)[scroll viewWithTag:100+i];
        NSString *path = [[[PMGlobal getInstance] getImageURL] stringByAppendingPathComponent:obj.pThumbURL];
        path = [path stringByReplacingOccurrencesOfString:@"http:/" withString:@"http://"];
        UIImage *img = [imageCache_ imageForKey:obj.pThumbURL url:[NSURL URLWithString:path] queueIfNeeded:YES tag:v.tag];
        if (img==nil || ![[PMGlobal getInstance]isImageEnable]) {
            img = [[UIHelper getInstance] getBundleImage:@"product_placeholder.jpg"];;
        }
        v.imageview.image = img;
    }
    for (int i=(page1+2)*PRONUM; i<page*PRONUM; i++) {
        ProductThumbView *v = (ProductThumbView *)[scroll viewWithTag:100+i];
        v.imageview.image = [[UIHelper getInstance] getBundleImage:@"product_placeholder.jpg"];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 6.0) {
        if (self.isViewLoaded && !self.view.window)
        {
            self.view = nil;
        }
    }
}

#pragma mark 过滤条件按钮点击事件
- (void)keyClicked:(UIButton *)sender{
    
    if (isclear == YES) {
  //  UIButton *btn = (UIButton *)[tint viewWithTag:sender.tag];
  //  [btn setBackgroundColor:[UIColor colorWithRed:192/255.0 green:192/255.0 blue:192/255.0 alpha:1]];
  //      [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
  //      [btn setImage:nil forState:UIControlStateNormal];
        
  //  [popUp removeFromSuperview];
    
        int category = sender.tag;
            cleartag = sender.tag;
        

        //先获取点击的按钮的当前过滤条件，以此得到父ID
        KeyObject* key = [KeyFilter objectAtIndex:category-1];
        
        //若父ID为0则表示无上级目录，直接取这个过滤条件的所有项
        NSArray* arr;
        if (key.parentCode==0) {
            arr = [[DataManager sharedManager]getKeyObjects:category];
        }
        else{
            //有上次则根据上次获取该父亲下的所有子目录
            arr = [[DataManager sharedManager]getChildrenKeyObjects:key.parentCode];
        }
        
        controller = [[DemoTableController alloc] initWithStyle:UITableViewStylePlain items:arr tag:sender.tag];
        
        
        FPPopoverController *popover = [[FPPopoverController alloc] initWithViewController:controller];
        popover.distance = distance;
        //popover.arrowDirection = FPPopoverArrowDirectionAny;
        popover.tint = FPPopoverDefaultTint;
        
        if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
        {
            popover.contentSize = CGSizeMake(200, 500);
        }
        popover.arrowDirection = FPPopoverArrowDirectionUp;
        
        //sender is the UIButton view
        sender.left -=distance;
        [popover presentPopoverFromView:sender];
        sender.left +=distance;
        
  //  popUp = [[PopupView alloc] initWithFrame:sender.frame withItems:items withHighlight:0 width:sender.left+35 tag:sender.tag];
  //  popUp.delegate = self;
  //  [self.view addSubview:popUp];
      //  isclear = NO;
    }
    else
    {
        UIButton *btn = (UIButton *)[tint viewWithTag:cleartag];
        [btn setBackgroundColor:[UIColor clearColor]];
        [btn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        [btn setImage:[[UIHelper getInstance] getBundleImage:@"order_next.png"] forState:UIControlStateNormal];
        //[popUp removeFromSuperview];
        isclear = YES;
    }
     
    /*
    DemoTableController *controller = [[DemoTableController alloc] initWithStyle:UITableViewStylePlain];
    
    FPPopoverController *popover = [[FPPopoverController alloc] initWithViewController:controller];
    
    //popover.arrowDirection = FPPopoverArrowDirectionAny;
    popover.tint = FPPopoverDefaultTint;
    
    if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
    {
        popover.contentSize = CGSizeMake(300, 500);
    }
    popover.arrowDirection = FPPopoverArrowDirectionUp;
    
    //sender is the UIButton view
    [popover presentPopoverFromView:sender];
     */
}

//根据当前选择的过滤条件来更新其他条件内容
- (void)updateKeyButton:(int)selectedCategory{
    
    KeyObject* key = [KeyFilter objectAtIndex:selectedCategory-1];
    
    UIButton* btn = (UIButton*)[filterBtns_ objectAtIndex:key.categoryCode-1];
   // [btn setImage:[[UIHelper getInstance] getBundleImage:@"order_next.png"] forState:UIControlStateNormal];
    [btn setTitle:key.keyName forState:UIControlStateNormal];
    
    CGSize s = [key.keyName sizeWithFont:btn.titleLabel.font];
    if (s.width>98) {
        btn.imageEdgeInsets = UIEdgeInsetsMake(0, 90+(98-56)/2, 0, 0);
    }
    else
    {
        btn.imageEdgeInsets = UIEdgeInsetsMake(0, 90+(s.width-56)/2, 0, 0);
    }
    //层层往下找，是否有连动的子级菜单
    NSArray*child = [[DataManager sharedManager]getChildrenKeyObjects:key.keyID];
    
    if (child.count>0) {
        //取第一个值作为过滤条件
        KeyObject *firstchild = [child objectAtIndex:0];
        
        [KeyFilter replaceObjectAtIndex:firstchild.categoryCode-1 withObject:firstchild];
        
        UIButton* btn = (UIButton*)[filterBtns_ objectAtIndex:firstchild.categoryCode-1];
        
        [btn setTitle:firstchild.keyName forState:UIControlStateNormal];
        
        //如果能找到子集菜单则递归调用子集
        [self updateKeyButton:firstchild.categoryCode];
    }
    
}

//- (void)updateKeyButton:(UIButton *)button withIndex:(int)targetIndex{
//    int cat = button.tag;
//    
//    NSArray *keys = [self getCategoryObject:cat];
//    KeyObject *obj = [keys objectAtIndex:targetIndex];
//    [button setTitle:obj.keyName forState:UIControlStateNormal];
//    
//    NSArray *children = [[DataManager sharedManager] getChildrenKeyObjects:obj.keyID];
//    if (children.count>0) {
//        KeyObject *child = [children objectAtIndex:0];
//        UIButton *childBtn = [self getFilterButtonByCode:child.categoryCode];
//        [childBtn setTitle:@"全部" forState:UIControlStateNormal];
//       // [self updateKeyButton:childBtn withIndex:0];
//    }
//    [self refresh:obj.keyName style:nil];
//    pserialstr = obj.keyName;
//}
//- (void)updateKeyButton1:(UIButton *)button withIndex:(int)targetIndex{
//    int cat = button.tag;
//    
//    NSArray *keys = [self getCategoryObject:cat];
//    if (targetIndex == 0) {
//        [button setTitle:@"全部" forState:UIControlStateNormal];
//        [self refresh:pserialstr style:nil];
//    }
//    else
//    {
//        if (keys.count>0) {
//            KeyObject *obj = [keys objectAtIndex:targetIndex-1];
//            [button setTitle:obj.keyName forState:UIControlStateNormal];
//            [self refresh:pserialstr style:obj.keyName];
//            stylestr = obj.keyName;
//        }
//    }
//    
//}
#pragma mark
#pragma mark 过滤条件点击后更新数据
-(void)index:(NSNotification *)sender
{
    NSDictionary* dic =  sender.object;
    
    KeyObject* key = [dic objectForKey:@"key"];
    
    [KeyFilter replaceObjectAtIndex:[[dic objectForKey:@"category"]intValue]-1 withObject:key];
    
    [self updateKeyButton:[[dic objectForKey:@"category"]intValue]];
    
    [self refresh];
    
//    NSString *str = sender.object;
//    int index = [str intValue];
//    UIButton *b = [self getFilterButtonByCode:selectCategory_];
//    if (selectCategory_==1) {
//        [self updateKeyButton:b withIndex:index];
//    }
//    else
//    {
//        [self updateKeyButton1:b withIndex:index];
//    }
    [[NSNotificationCenter defaultCenter]postNotificationName:@"dismissPopover" object:nil];
}

#pragma mark 重新实例化search以防不能点击
-(void)addsearch:(NSNotification *)sender
{
    [search removeFromSuperview];
#ifdef DHH_iOS
    search = [[UITextField alloc]initWithFrame:CGRectMake(0, 0, 150, 23)];
    search.backgroundColor = [UIColor clearColor];
    search.center = CGPointMake(self.view.width/2, [[UIHelper getInstance] getBundleImage:@"iphone_tint.png"].size.height/2);
    search.delegate = self;
    search.keyboardType=UIKeyboardTypeNumbersAndPunctuation;
    search.returnKeyType = UIReturnKeySearch;
    [tint addSubview:search];
#else
    /*
    search = [[UITextField alloc]initWithFrame:CGRectMake(0, 0, 100, 23)];
    search.backgroundColor = [UIColor clearColor];
    search.center = CGPointMake(910, searchimage.height/2+2);
    search.delegate = self;
    search.keyboardType=UIKeyboardTypeNumbersAndPunctuation;
    search.returnKeyType = UIReturnKeySearch;
    [searchimage addSubview:search];
    */
    
    
#endif
}
//-(void)refreshorder:(NSNotification *)sender
//{
//    [self refresh:@"西装类" style:nil];
//}
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    [self refresh1];
    return YES;
}

#ifdef DHH_iOS
#else
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation{
    return UIInterfaceOrientationIsLandscape(toInterfaceOrientation);
}

- (BOOL)shouldAutorotate{
    return YES;
}

- (NSUInteger)supportedInterfaceOrientations{
    return UIInterfaceOrientationMaskLandscape;
}
#endif

#pragma mark 显示图片
- (void)product_image:(NSNotification *)notification{
    NSDictionary *dict = [notification userInfo];
    UIImage *img = [dict objectForKey:@"image"];
    int tag = [[dict objectForKey:@"tag"] intValue];
    
    ProductThumbView *v = (ProductThumbView *)[scroll viewWithTag:tag];
    if ([[PMGlobal getInstance]isImageEnable]) {
        if (img) {
            v.imageview.image = img;
        }else{
            
        }
        
    }else{
        v.imageview.image = [[UIHelper getInstance] getBundleImage:@"product_placeholder.jpg"];;
    }
    
}
-(void)zbar:(UIButton *)sender
{
    //    ZbarViewController *zbar = [[ZbarViewController alloc]init];
    //    [self.navigationController pushViewController:zbar animated:YES];
//    ZBarReaderViewController *reader = [ZBarReaderViewController new];
//    reader.readerDelegate = self;
//    reader.supportedOrientationsMask = ZBarOrientationMaskAll;
//#ifdef DHH_iOS
//    UIImage *img = [[UIHelper getInstance] getBundleImage:@"croprect_iphone.png"];
//    UIImageView *imageview = [[UIImageView alloc]initWithImage:img];
//    imageview.frame = CGRectMake(0, 0, img.size.width, img.size.height);
//    imageview.center = CGPointMake(160, 190);
//    [reader.view addSubview:imageview];
//    
//    img = [[UIHelper getInstance] getBundleImage:@"croptip_iphone.png"];
//    UIImageView *tipimageview = [[UIImageView alloc]initWithImage:img];
//    tipimageview.frame = CGRectMake(0, 0, img.size.width, img.size.height);
//    tipimageview.centerX = imageview.centerX;
//    tipimageview.top = imageview.bottom;
//    [reader.view addSubview:tipimageview];
//#else
//    UIImage *img = [[UIHelper getInstance] getBundleImage:@"croprect.png"];
//    UIImageView *imageview = [[UIImageView alloc]initWithImage:img];
//    imageview.frame = CGRectMake(0, 0, img.size.width, img.size.height);
//    imageview.center = CGPointMake(512, 368);
//    [reader.view addSubview:imageview];
//    
//    img = [[UIHelper getInstance] getBundleImage:@"croptip.png"];
//    UIImageView *tipimageview = [[UIImageView alloc]initWithImage:img];
//    tipimageview.frame = CGRectMake(0, 0, img.size.width, img.size.height);
//    tipimageview.centerX = imageview.centerX;
//    tipimageview.top = imageview.bottom;
//    [reader.view addSubview:tipimageview];
//#endif
//    CGRect scanMaskRect;
//    if ([[[UIDevice currentDevice] systemVersion] floatValue]>=7.0)
//    {
//        scanMaskRect = CGRectMake(0, 0, imageview.size.width, imageview.size.height);
//    }
//    else
//    {
//        scanMaskRect = CGRectMake(0, 0, 1024, 768);
//    }
//    reader.scanCrop = [self getScanCrop:scanMaskRect readerViewBounds:reader.view.bounds];
//    
//    ZBarImageScanner *scanner = reader.scanner;
//    
//    [scanner setSymbology: ZBAR_I25
//                   config: ZBAR_CFG_ENABLE
//                       to: 0];
//    
//    [self presentModalViewController: reader
//                            animated: YES];
}
//- (void) imagePickerController: (UIImagePickerController*) reader
// didFinishPickingMediaWithInfo: (NSDictionary*) info
//{
//    id<NSFastEnumeration> results =
//    [info objectForKey: ZBarReaderControllerResults];
//    ZBarSymbol *symbol = nil;
//    for(symbol in results)
//        break;
//    
//    zbarimageview.image =
//    [info objectForKey: UIImagePickerControllerOriginalImage];
//    
//    [reader dismissModalViewControllerAnimated: YES];
//    
//    //判断是否包含 头'http:'
//    NSString *regex = @"http+:[^\\s]*";
//    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
//    
//    //判断是否包含 头'ssid:'
//    NSString *ssid = @"ssid+:[^\\s]*";;
//    NSPredicate *ssidPre = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",ssid];
//    
//   // zbarlabel.text =  symbol.data ;
//    int cnt =[[[DataManager sharedManager]searchProductCountWithSimCode:symbol.data]intValue];
//    if(cnt == 0)
//    {
//        NSString *str=[NSString stringWithFormat:@"没有找到简码%@",symbol.data];
//        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:str delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
//        [alert show];
//    }
//    else if(cnt >= 1){
//        searchproduct = [[DataManager sharedManager]searchProductWithSimCode:symbol.data];
//        ProductObject *obj = [searchproduct objectAtIndex:0];
////        ProductDetailViewController *detail = [[ProductDetailViewController alloc] initWithProduct:obj objtag:1 tag:1];
//        ProductDetailViewControllerEx *detail = [[ProductDetailViewControllerEx alloc] initWithProduct:obj];
//        detail.hidesBottomBarWhenPushed = YES;
//
//        [self.navigationController pushViewController:detail animated:YES];
//    }
//    if ([predicate evaluateWithObject:zbarlabel.text]) {
//        
//        UIAlertView * alert = [[UIAlertView alloc]initWithTitle:nil
//                                                        message:@"It will use the browser to this URL。"
//                                                       delegate:nil
//                                              cancelButtonTitle:@"Close"
//                                              otherButtonTitles:@"Ok", nil];
//        alert.delegate = self;
//        alert.tag=1;
//        [alert show];
//        
//        
//        
//    }
//    else if([ssidPre evaluateWithObject:zbarlabel.text]){
//        
//        NSArray *arr = [zbarlabel.text componentsSeparatedByString:@";"];
//        
//        NSArray * arrInfoHead = [[arr objectAtIndex:0] componentsSeparatedByString:@":"];
//        
//        NSArray * arrInfoFoot = [[arr objectAtIndex:1] componentsSeparatedByString:@":"];
//        
//        
//        zbarlabel.text=
//        [NSString stringWithFormat:@"ssid: %@ \n password:%@",
//         [arrInfoHead objectAtIndex:1],[arrInfoFoot objectAtIndex:1]];
//        
//        
//        UIAlertView * alert = [[UIAlertView alloc]initWithTitle:zbarlabel.text
//                                                        message:@"The password is copied to the clipboard , it will be redirected to the network settings interface"
//                                                       delegate:nil
//                                              cancelButtonTitle:@"Close"
//                                              otherButtonTitles:@"Ok", nil];
//        
//        
//        alert.delegate = self;
//        alert.tag=2;
//        [alert show];
//        
//        UIPasteboard *pasteboard=[UIPasteboard generalPasteboard];
//        //        然后，可以使用如下代码来把一个字符串放置到剪贴板上：
//        pasteboard.string = [arrInfoFoot objectAtIndex:1];
//        
//        
//    }
//}

#pragma mark 消息更新弹出框
-(void)showtip:(NSNotification *)sender
{
    NSArray *tips = [[DataManager sharedManager]getTipsarray];
    if (tips.count==0) {
        return;
    }
    NSDictionary *tipdic = [tips objectAtIndex:tips.count-1];
    
    [self performSelectorOnMainThread:@selector(addTipView:) withObject:tipdic waitUntilDone:YES];
    
}

- (void)addTipView:(NSDictionary *)dic{
    TipView *tipview = [[TipView alloc]initWithdic:dic];
    [self.navigationController.view addSubview:tipview];
}

-(void)viewTapped:(UITapGestureRecognizer*)tapGr {
    [search resignFirstResponder];
}

-(CGRect)getScanCrop:(CGRect)rect readerViewBounds:(CGRect)readerViewBounds
{
    CGFloat x,y,width,height;
    
    x = rect.origin.x / readerViewBounds.size.width;
    y = rect.origin.y / readerViewBounds.size.height;
    width = rect.size.width / readerViewBounds.size.width;
    height = rect.size.height / readerViewBounds.size.height;
    
    return CGRectMake(x, y, width, height);
}

-(void)selectcode:(UIButton *)sender
{
    //[codesearch removeFromSuperview];
    if(isclick == NO)
    {
        search.placeholder = SEARCH_CODENAME;
        // [sender setTitle:@"简码搜索" forState:UIControlStateNormal];
        showMessage([NSString stringWithFormat:@"切换成%@",SEARCH_CODENAME]);
        isclick = YES;
        [[NSNotificationCenter defaultCenter]postNotificationName:@"setsearchbtn" object:@"0"];
        NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
        [def setObject:@"1" forKey:@"setsearchbtn"];
        [def synchronize];
    }
    else
    {
        search.placeholder = SEARCH_SIMCODE;
        showMessage([NSString stringWithFormat:@"切换成%@",SEARCH_SIMCODE]);
        isclick = NO;
        [[NSNotificationCenter defaultCenter]postNotificationName:@"setsearchbtn" object:@"1"];
        NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
        [def setObject:@"0" forKey:@"setsearchbtn"];
        [def synchronize];
    }
}

- (void)comfirmSearch:(UIButton *)button{
    [self refresh1];
}

-(void)clicktap:(UITapGestureRecognizer *)sender
{
    [self refresh1];
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    if ([touch.view isKindOfClass:[UIControl class]]) {
        // we touched a button, slider, or other UIControl
        return NO; // ignore the touch
    }
    return YES; // handle the touch
}

-(void)setsearchbtn1:(NSNotification *)sender
{
    NSString *str = sender.object;
    if([str isEqualToString:@"0"])
    {
        search.placeholder = SEARCH_CODENAME;
        showMessage([NSString stringWithFormat:@"切换成%@",SEARCH_CODENAME]);
        isclick = YES;
    }
    else
    {
        search.placeholder = SEARCH_SIMCODE;
        showMessage([NSString stringWithFormat:@"切换成%@",SEARCH_SIMCODE]);
        isclick = NO;
    }
}
@end
